/**
 * Description : 模仿对数据库的操作，此模块用于对 pesist/db.json 文件进行增删改查
 */

const fs = require('fs')
const dbpath = './pesist/db_user.json' // 数据库路径
const default_dbpath = './pesist/db_donot_modify.json' // 默认数据库




// 获取完整的数据库内容
exports.find = function (callback) {
  fs.readFile(dbpath, 'utf8', (err, data) => {
    if (err) {
      callback(err)
    }
    let db = JSON.parse(data)
    callback(null, db)
  })
}

// 获取指定id的内容，data 是书签 "bookmarks" 对象
exports.findById = function (id, callback) {
  fs.readFile(dbpath, 'utf8', (err, data) => {
    if (err) {
      callback(err)
    }
    let _cate = `bk${id[0]}`
    let targetArr = JSON.parse(data).bookmarks[_cate]
    let targetElem = targetArr.find((item) => item.id == id)
    callback(null, targetElem)
  })
}

// 将传过来的信息 写入 db
exports.add = function (info, callback) {
  fs.readFile(dbpath, 'utf8', (err, data) => {
    if (err) {
      callback(err)
    }
    let _cate = `bk${info.type}`
    let db = JSON.parse(data)
    let targetArr = db.bookmarks[_cate]
    let _newID = Number.parseInt(targetArr[targetArr.length - 1].id) + 1
    let tempstr = {
      id : _newID + '',
      name : info.name,
      picsrc : info.picsrc,
      netaddr : info.netaddr
    }
    targetArr.push(tempstr)

    let fileDate = JSON.stringify(db, null, 2)

    fs.writeFile(dbpath, fileDate, (err) => {
      if (err) {
        callback(err)
      }
      callback(null)
    })
  })
}


// 更新数据库
exports.update = function(info, callback) {
  fs.readFile(dbpath, 'utf8', (err, data) => {
    if (err) {
      callback(err)
    }
    let _cate = `bk${info.type}`
    let db = JSON.parse(data)
    let targetArr = db.bookmarks[_cate]
    let targetElem = targetArr.find((item) => item.id == info.id)
    
    for (let key in targetElem) {
      targetElem[key] = info[key]
    }

    let fileDate = JSON.stringify(db, null, 2)

    fs.writeFile(dbpath, fileDate, (err) => {
      if (err) {
        callback(err)
      }
      callback(null)
    })
  })
}


exports.dropById = function (id, callback) {
  fs.readFile(dbpath, 'utf8', (err, data) => {
    if (err) {
      callback(err)
    } else {
      let _cate = `bk${id[0]}`
      let db = JSON.parse(data)
      let targetArr = db.bookmarks[_cate]
      let targetIndex = targetArr.findIndex((item) => item.id == id)

      targetArr.splice(targetIndex, 1) // 删除这个数组元素

      let fileDate = JSON.stringify(db, null, 2)

      fs.writeFile(dbpath, fileDate, (err) => {
        if (err) {
          callback(err)
        }
        callback(null)
      })
    }
  })
}

// 恢复数据库到默认状态
exports.reset = function(callback) {
  fs.readFile(default_dbpath, 'utf8', (err, data) => {
    if (err) {
      callback(err)
    }
    fs.writeFile(dbpath, data, (err) => {
        if (err) {
          callback(err)
        }
        callback(null)
    })
  })
}
